import { contextBridge, ipcRenderer } from 'electron'

// 添加调试日志
console.log('预加载脚本执行开始')

// 为了解决TypeScript错误，声明全局window接口
declare global {
  interface Window {
    electronAPI: any;
  }
}

// --------- 暴露一些API给渲染进程 ---------
contextBridge.exposeInMainWorld('electronAPI', {
  // 接收来自主进程的菜单操作信息
  onMenuAction: (callback: (data: any) => void) => {
    console.log('注册菜单操作监听器')
    ipcRenderer.on('menu-action', (_event, data) => callback(data))
  },
  
  // 移除菜单操作监听器
  removeMenuActionListener: () => {
    ipcRenderer.removeAllListeners('menu-action')
  },

  // 文件操作
  fileOperation: (data: any) => ipcRenderer.invoke('file-operation', data),
  
  // 打开新窗口
  openWindow: (hash: string) => {
    ipcRenderer.invoke('open-win', { hash })
  },

  // 获取当前平台
  platform: process.platform,
  
  // 版本信息
  versions: {
    chrome: process.versions.chrome,
    node: process.versions.node,
    electron: process.versions.electron
  },
  
  // 接收来自主进程的一般消息
  onMessage: (callback: (message: string) => void) => {
    console.log('注册主进程消息监听器')
    ipcRenderer.on('main-process-message', (_event, message) => {
      console.log('收到主进程消息:', message)
      callback(message)
    })
  },
  
  // 窗口控制
  minimizeWindow: () => ipcRenderer.send('window-control', 'minimize'),
  maximizeWindow: () => ipcRenderer.send('window-control', 'maximize'),
  closeWindow: () => ipcRenderer.send('window-control', 'close'),
  
  // 检查更新
  checkForUpdates: () => ipcRenderer.invoke('check-for-updates'),
  downloadUpdate: () => ipcRenderer.invoke('download-update'),
  installUpdate: () => ipcRenderer.invoke('install-update'),
  
  // 更新事件监听
  onUpdateAvailable: (callback: (info: any) => void) => {
    ipcRenderer.on('update-available', (_event, info) => callback(info))
  },
  onUpdateNotAvailable: (callback: () => void) => {
    ipcRenderer.on('update-not-available', () => callback())
  },
  onUpdateProgress: (callback: (progressObj: any) => void) => {
    ipcRenderer.on('update-progress', (_event, progressObj) => callback(progressObj))
  },
  onUpdateDownloaded: (callback: () => void) => {
    ipcRenderer.on('update-downloaded', () => callback())
  },
  onUpdateError: (callback: (err: any) => void) => {
    ipcRenderer.on('update-error', (_event, err) => callback(err))
  }
})

// 设置一个函数来支持Vue应用的热更新
const replaceText = (selector: string, text: string) => {
  const element = document.getElementById(selector)
  if (element) element.innerText = text
}

window.addEventListener('DOMContentLoaded', () => {
  console.log('DOM加载完成，设置版本信息')
  for (const dep of ['chrome', 'node', 'electron']) {
    replaceText(`${dep}-version`, process.versions[dep as keyof NodeJS.ProcessVersions] || '')
  }
})

console.log('预加载脚本执行完成')
